package socket;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;

public class EchoClient {

    public static void main(String[] args) {
        boolean connected = false;
        Socket client = null;
        PrintWriter writer = null;
        BufferedReader reader = null;

        try {
            client = new Socket();
            client.connect(new InetSocketAddress("localhost", 8000));
            connected = true;

            writer = new PrintWriter(client.getOutputStream(), true);
            reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            final BufferedReader finalReader = reader;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String inputLine = null;
                    if (finalReader == null) {
                        return;
                    }
                    try {
                        while ( (inputLine = finalReader.readLine()) != null) {
                            System.out.println("from server: " + inputLine);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }).start();


            BufferedReader reader1 = new BufferedReader(new InputStreamReader(System.in));
            String say = null;
            while ((say = reader1.readLine()) != null
                    && !say.equals("exit") && !say.equals("quit")) {
                writer.println(say);
                writer.flush();
            }
            disConnect(client, writer, reader);


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            disConnect(client, writer, reader);
        }
    }

    private static void disConnect(Socket client, PrintWriter writer, BufferedReader reader) {
        try {
            if (writer != null) {
                writer.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (client != null) {
                client.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
